package org.jheuristics.ga.operators;

import java.util.Iterator;

import org.epanetgrid.otimizacao.log.AGLogger;
import org.epanetgrid.otimizacao.util.OtimizacaoUtil;
import org.jheuristics.DefaultIndividual;
import org.jheuristics.Individual;
import org.jheuristics.ga.DefaultPopulation;
import org.jheuristics.ga.GAConfig;
import org.jheuristics.ga.GAStatus;
import org.jheuristics.ga.Operator;
import org.jheuristics.ga.Population;


/**
 * TODO
 *
 * @author Marcell Manfrin, marcell@ourgrid.org, Jan 9, 2006
 */
public class IndividualsInsertionOperator implements Operator {
    private PopulationChooser chooser;
    private Population individuals;

    /**
     * TODO
     *
     * @param chooser
     */
    public IndividualsInsertionOperator(PopulationChooser chooser) {
        setPopulationChooser(chooser);
        individuals = new DefaultPopulation();
    }

    /**
     * TODO
     *
     * @param status
     * @param config
     * @see org.jheuristics.ga.Operator#operate(org.jheuristics.ga.GAStatus, org.jheuristics.ga.GAConfig)
     */
    public void operate(GAStatus status, GAConfig config) {
        if (individuals.size() > 0) {
            synchronized (this) {
                Population toPop = chooser.choose(status, config);
                for (Iterator it = individuals.iterator(); it.hasNext(); ) {
                    Individual individual = (Individual) it.next();
                    if (!toPop.contains(individual)) {
        				StringBuffer buffer = new StringBuffer("Seeding: Adicionando indivíduo à população:\n");
        				buffer.append(OtimizacaoUtil.format(individual));
        				AGLogger.getInstance().debug(buffer);
                        toPop.addIndividual(individual);
                    }
                }
                individuals.clear();
            }
        }
    }

    /**
     * TODO
     *
     * @return
     */
    public PopulationChooser getPopulationChooser() {
        return chooser;
    }

    /**
     * TODO
     *
     * @param chooser
     */
    public void setPopulationChooser(PopulationChooser chooser) {
        if (null == chooser) {
            // TODO: ERROR MSG
            throw new NullPointerException();
        }
        this.chooser = chooser;
    }

    /**
     * TODO
     *
     * @param individual
     */
    public synchronized void addIndividual(Individual individual) {
        individuals.addIndividual(individual);
    }

}
